<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	require_once dirname(BASEPATH) . '/application/libraries/facebook/facebook.php';
	
	class facebook_api extends Facebook{		
		public $facebook_app_id;
		public $facebook_secret;
		public $facebook_fanpage_id;
		
		function facebook_api($init=true){
			$this->facebook_app_id = '390661077691722';
			$this->facebook_secret = '1e4131b0d6869b9ebf23da97510525da';
			$this->facebook_fanpage_id = '522278907818821';			
			
			if ($init){				
				$config = array('appId' => $this->facebook_app_id,
								'secret' => $this->facebook_secret);
				parent::__construct($config);
			}
		}
		function fanpage_info($fanpage_url)
		{			
			$fanpage_url = str_replace("http://", "", $fanpage_url);						
			$path_arr = explode("/", $fanpage_url);
			
			$url = 'http://graph.facebook.com/' . $path_arr[1];
			return json_decode(file_get_contents($url));		
		}
		
		function parse_signed_request($signed_request) {
			list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

			// decode the data
			$sig = $this->base64_url_decode($encoded_sig);
			$data = json_decode($this->base64_url_decode($payload), true);
			
			if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
				error_log('Unknown algorithm. Expected HMAC-SHA256');
				return null;
			}
			
			// check sig
			$expected_sig = hash_hmac('sha256', $payload, $this->facebook_secret, $raw = true);
			if ($sig !== $expected_sig) {
				error_log('Bad Signed JSON signature!');
				return null;
			}

  			return $data;
		}
		function base64_url_decode($input) {
			return base64_decode(strtr($input, '-_', '+/'));
		}
		
		function get_user($option='/me'){
			$user = $this->getUser();
			$user_info = null;
			if ($user) {
				try {
					$user_info =  $this->api($option);
				} catch (FacebookApiException $e) {
					$user = null;
				}
			}
			
			return $user_info;
		}
		function get_user_avatar($uid=null){
			if (is_null($uid) || empty($uid))
				return base_url() . 'images/no_img_avatar.png';
			else
				return 'https://graph.facebook.com/' . $uid . '/picture';
		}
		function get_user_id(){
			$user = $this->get_user();
			return $user['id'];
		}
		function remove_app($uid){
			$this->api('/' . $this->facebook_app_id . '_' . $uid, 'DELETE');
		} 
	}
?>